package com.scorpio.pay.service.impl;

import com.scorpio.order.domain.OrderEntity;
import com.scorpio.order.enums.OrderStatusEmun;
import com.scorpio.order.service.OrderService;
import com.scorpio.order.service.OrderSnsServer;
import com.scorpio.pay.enums.PayTypeEnum;
import com.scorpio.pay.service.CallbackService;
import com.scorpio.redis.cachelock.RedisLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class CallbackServiceImpl implements CallbackService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean wxPayNotification(String orderSn, String trade_no, int total_fee) {
        return payNotification(PayTypeEnum.WeChatPay, orderSn, trade_no, total_fee);
    }

    public boolean payNotification(PayTypeEnum payTypeEnum, String orderSn, String trade_no, int total_fee) {
        String key = "PayNotification:" + orderSn;
        if (redisLock.lock(key, 10)) {
            try {
                OrderEntity entity = orderService.selectByOrderOn(orderSn);
                if (entity == null) return false;
                if (!OrderStatusEmun.Status0.getValue().equals(entity.getStatus())) return true;
                entity.setPayTime(new Date());
                entity.setTransactionSn(trade_no);
                entity.setStatus(OrderStatusEmun.Status2.getValue());
                entity.setPayType(payTypeEnum.getValue());
                if (orderService.update(entity) > 0) {
                    orderSnsServer.saveMoney(orderSn, total_fee / 100f);
                    return true;
                }
                return true;
            } finally {
                redisLock.unlock(key);
            }
        }
        return false;
    }

    @Autowired
    private RedisLock redisLock;

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderSnsServer orderSnsServer;

}
